package com.happle.gcmclient;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;

import com.happle.gcmclient.adapter.SettingsLngAdapter;
import com.happle.gcmclient.adapter.SettingsLngAdapter.DeleteLanguageListener;
import com.happle.gcmclient.backendmanager.BackendManager;
import com.happle.gcmclient.backendmanager.task.UpdateLanguageTask;
import com.happle.gcmclient.config.CommonUtilities;
import com.happle.gcmclient.config.Constants;
import com.happle.gcmclient.config.GlobalValue;
import com.happle.gcmclient.customizewidget.NoScrollListView;
import com.happle.gcmclient.dialog.AddLanguageDialog;
import com.happle.gcmclient.dialog.AddLanguageDialog.SelectLanguageListener;
import com.happle.gcmclient.managers.LngManager;
import com.happle.gcmclient.obj.LngObj;

/**
 * Created by Inna on 03.11.13.
 */
public class SettingsActivity extends BaseActivity {

	public static final String TAG = "SettingsActivity";
	protected UpdateLanguageTask updLngTask;
	private NoScrollListView lsvLanguages;
	private CheckBox chkSettingSound, chkSettingVibrate;
	private List<LngObj> listLanguages;
	private SettingsLngAdapter settingsLngAdapter;
	private LngManager lngManager;
	private Button btnAddLng;
	private String[] items;
	private Spinner spnLanguage;
    private ArrayAdapter<String> lngAdapter;
	private TextView lblTitleSound, lblTitleVibrate, lblTitleLanguage,
			lblTitleSettingLanguage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings_layout);
		initUI();
		initData();
		// setToggleSettings();
		bindDataToList();
	}

	private void initUI() {

		initHeader();
		setHeaderTitle(getString(R.string.titleSettingsActivity), Constants.TITLE_SETTINGS_IMAGE_NUM);
		spnLanguage = (Spinner) findViewById(R.id.spnLanguage);
        items = getResources().getStringArray(R.array.arrLanguage);
        lngAdapter = new ArrayAdapter<String>(this,
                R.layout.simple_spinner_item_short, items);
        lngAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
        spnLanguage.setAdapter(lngAdapter);
		lsvLanguages = (NoScrollListView) findViewById(R.id.lsvLanguages);
		btnAddLng = (Button) findViewById(R.id.btnAddLanguage);
		btnAddLng.setOnClickListener(addLngListener);
		chkSettingSound = (CheckBox) findViewById(R.id.checkboxSound);
		chkSettingVibrate = (CheckBox) findViewById(R.id.checkboxVibrate);
		// Set event
		chkSettingSound.setOnCheckedChangeListener(onSettingSound);
		chkSettingVibrate.setOnCheckedChangeListener(onSettingVibrate);
		chkSettingSound.setChecked(CommonUtilities.getInstance(self)
				.getSettingSound());
		chkSettingVibrate.setChecked(CommonUtilities.getInstance(self)
				.getSettingVibrate());
		spnLanguage.setOnItemSelectedListener(onLanguageSettingChange);
		lblTitleLanguage = (TextView) findViewById(R.id.lblTiteLanage);
		lblTitleSettingLanguage = (TextView) findViewById(R.id.lblTitleLanguageSetting);
		lblTitleSound = (TextView) findViewById(R.id.lblTitleSound);
		lblTitleVibrate = (TextView) findViewById(R.id.lblTitleVibrate);
		spnLanguage.setSelection(CommonUtilities.getInstance(self).getIntValue(
				CommonUtilities.SETTING_LANGUAGE));
        //spnLanguage.setAdapter();
	}

	OnItemSelectedListener onLanguageSettingChange = new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			CommonUtilities.getInstance(self).putIntValue(
					CommonUtilities.SETTING_LANGUAGE,
					spnLanguage.getSelectedItemPosition());
			if (arg2 == 1)
				setLocale("he");
			else if (arg2 == 2)
				setLocale("vi");
            else if (arg2 == 3)
                setLocale("ru");
            else
                setLocale("en");
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}
	};

	private void setLocale(String localeCode) {
		Locale locale = new Locale(localeCode);
		Locale.setDefault(locale);
		Configuration config = new Configuration();
		config.locale = locale;
		onConfigurationChanged(config);
		getBaseContext().getResources().updateConfiguration(config,
				getBaseContext().getResources().getDisplayMetrics());
		reloadLanguage();
		CommonUtilities.getInstance(self).putStringValue(
				CommonUtilities.SETTING_LANGUAGE_CODE, localeCode);
	}

	private void reloadLanguage() {

		lblTitleLanguage.setText(R.string.settings_language);
		lblTitleVibrate.setText(R.string.btn_switch_vibration);
		lblTitleSound.setText(R.string.btn_switch_sound);
		lblTitleSettingLanguage.setText(R.string.settings_lng_title);
		setHeaderTitle(getString(R.string.titleSettingsActivity), Constants.TITLE_SETTINGS_IMAGE_NUM);
		btnAddLng.setText(R.string.btn_add_lng);
		updateStatusTitle();

	}

	OnCheckedChangeListener onSettingSound = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			CommonUtilities.getInstance(self).settingSound(isChecked);

		}
	};

	OnCheckedChangeListener onSettingVibrate = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			CommonUtilities.getInstance(self).settingVibrate(isChecked);
		}
	};

	private View.OnClickListener addLngListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			// showLngDialog();
			new AddLanguageDialog(self, new SelectLanguageListener() {
				@Override
				public void onSelect(int index, LngObj languageObject,
						List<LngObj> listLanguages) {
					updateLsvLng(languageObject);
					new updateLanguageTask(languageObject).execute();
				}
			}).show();
		}
	};

	private void initData() {
		listLanguages = new ArrayList<LngObj>();
		if (lngManager == null) {
			lngManager = new LngManager(self);
		}
		listLanguages = lngManager.getSelectedLanguages(true);

	}

	private void bindDataToList() {
		settingsLngAdapter = new SettingsLngAdapter(self, listLanguages,
				new DeleteLanguageListener() {

					@Override
					public void onDeleteLanguage(LngObj language) {
						// TODO Auto-generated method stub
						deleteSelectedLanguage(language);
					}
				});
		lsvLanguages.setAdapter(settingsLngAdapter);
	}

	public void deleteSelectedLanguage(LngObj newLngObj) {
		if (newLngObj != null) {
			newLngObj.set_is_marked(false);
			// update at server
			if (lngManager == null) {
				lngManager = new LngManager(self);
			}
			listLanguages.remove(newLngObj);
			settingsLngAdapter.notifyDataSetChanged();
			new updateLanguageTask(newLngObj).execute();
		}
	}

	private void updateLsvLng(LngObj newLngObj) {
		if (listLanguages == null)
			listLanguages = new ArrayList<LngObj>();
		listLanguages.add(newLngObj);
		settingsLngAdapter.notifyDataSetChanged();
	}

	private class updateLanguageTask extends AsyncTask<Void, Void, Integer> {
		private LngObj lng;

		public updateLanguageTask(LngObj lng) {
			this.lng = lng;
		}

		@Override
		protected Integer doInBackground(Void... params) {
			
			BackendManager bManager = new BackendManager();
			int taskResult = -1;
			try {
				taskResult = bManager.updateLanguage(lng, GlobalValue.registerId);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return taskResult;
		}

		@Override
		protected void onPostExecute(Integer result) {
			closeProgressDialog();
			lng.set_is_sent((result == 1) ? true : false);
			// Update local database
			lngManager.updateLngSettings(lng);
		}

		@Override
		protected void onPreExecute() {
			showProgressDialog();
		}

	}
}
